/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 悬浮播放器服务 - 管理显示条件和状态监听
 * 
 * 功能特性：
 * - 监听 MusicPlayerViewModel 状态变化
 * - 自动控制悬浮播放器的显示/隐藏
 * - 管理页面切换时的显示逻辑
 * - 提供便捷的控制接口
 */

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../viewmodels/music_player_view_model.dart';
import 'floating_ui_manager.dart';

/// 悬浮播放器服务
/// 负责管理悬浮播放器的显示逻辑和状态同步
class FloatingPlayerService {
  static FloatingPlayerService? _instance;
  static FloatingPlayerService get instance =>
      _instance ??= FloatingPlayerService._();

  FloatingPlayerService._();

  /// 是否在播放页面
  bool _isInPlayerPage = false;

  /// MusicPlayerViewModel 监听器
  VoidCallback? _playerViewModelListener;

  /// 初始化服务
  static void initialize(BuildContext context) {
    final service = FloatingPlayerService.instance;

    // 保存 context 引用
    service._context = context;

    // 确保 FloatingPlayerManager 已初始化
    FloatingPlayerManager.initialize(context);

    // 设置监听器
    service._setupPlayerViewModelListener(context);
  }

  /// MusicPlayerViewModel 引用
  MusicPlayerViewModel? _musicPlayerViewModel;

  /// 设置播放器 ViewModel 监听器
  void _setupPlayerViewModelListener(BuildContext context) {
    _musicPlayerViewModel =
        Provider.of<MusicPlayerViewModel>(context, listen: false);

    _playerViewModelListener = () {
      _handlePlayerStateChange(_musicPlayerViewModel!);
    };

    // 监听播放状态变化
    _musicPlayerViewModel!.isPlaying.addListener(_playerViewModelListener!);
    _musicPlayerViewModel!.addListener(_playerViewModelListener!);
  }

  /// BuildContext 引用（弱引用，用于更新 UI）
  BuildContext? _context;

  /// 处理播放器状态变化
  void _handlePlayerStateChange(MusicPlayerViewModel viewModel) {
    // 更新悬浮播放器的播放状态
    if (FloatingPlayerManager.isShowing && _context != null) {
      FloatingPlayerManager.updatePlayingState(_context!);
    }

    // 根据播放状态和页面状态决定是否显示悬浮播放器
    _updateFloatingPlayerVisibility(viewModel);
  }

  /// 更新悬浮播放器可见性
  void _updateFloatingPlayerVisibility(MusicPlayerViewModel viewModel) {
    if (_context == null) return;

    final shouldShow = _shouldShowFloatingPlayer(viewModel);

    if (shouldShow && !FloatingPlayerManager.isShowing) {
      FloatingPlayerManager.show(_context!);
    } else if (!shouldShow && FloatingPlayerManager.isShowing) {
      FloatingPlayerManager.hide();
    }
  }

  /// 判断是否应该显示悬浮播放器
  bool _shouldShowFloatingPlayer(MusicPlayerViewModel viewModel) {
    // 必须有当前播放的音乐
    if (!viewModel.hasCurrentTrack) {
      return false;
    }

    // 不在播放页面时才显示
    if (_isInPlayerPage) {
      return false;
    }

    return true;
  }

  /// 页面进入播放页面
  static void enterPlayerPage(BuildContext context) {
    final service = FloatingPlayerService.instance;
    service._isInPlayerPage = true;

    // 隐藏悬浮播放器
    if (FloatingPlayerManager.isShowing) {
      FloatingPlayerManager.hide();
    }
  }

  /// 页面离开播放页面
  static void exitPlayerPage([BuildContext? context]) {
    final service = FloatingPlayerService.instance;
    service._isInPlayerPage = false;

    // 更新 context 引用（如果提供）
    if (context != null) {
      service._context = context;
    }

    // 检查是否需要显示悬浮播放器
    if (service._musicPlayerViewModel != null && service._context != null) {
      if (service._shouldShowFloatingPlayer(service._musicPlayerViewModel!)) {
        FloatingPlayerManager.show(service._context!);
      }
    }
  }

  /// 设置当前路由
  static void setCurrentRoute(String? routeName) {
    final service = FloatingPlayerService.instance;

    // 根据路由判断是否在播放页面
    service._isInPlayerPage = routeName == '/music_player';
  }

  /// 手动显示悬浮播放器
  static void showFloatingPlayer(BuildContext context) {
    final service = FloatingPlayerService.instance;
    service._context = context;

    if (service._musicPlayerViewModel != null &&
        service._musicPlayerViewModel!.hasCurrentTrack) {
      FloatingPlayerManager.show(context);
    }
  }

  /// 手动隐藏悬浮播放器
  static void hideFloatingPlayer() {
    FloatingPlayerManager.hide();
  }

  /// 关闭悬浮播放器
  static void closeFloatingPlayer() {
    FloatingPlayerManager.close();
  }

  /// 切换悬浮播放器显示状态
  static void toggleFloatingPlayer(BuildContext context) {
    if (FloatingPlayerManager.isShowing) {
      hideFloatingPlayer();
    } else {
      showFloatingPlayer(context);
    }
  }

  /// 获取当前是否显示悬浮播放器
  static bool get isShowing => FloatingPlayerManager.isShowing;

  /// 销毁服务
  static void dispose() {
    final service = FloatingPlayerService.instance;

    // 移除监听器
    if (service._playerViewModelListener != null &&
        service._musicPlayerViewModel != null) {
      service._musicPlayerViewModel!.isPlaying
          .removeListener(service._playerViewModelListener!);
      service._musicPlayerViewModel!
          .removeListener(service._playerViewModelListener!);
      service._playerViewModelListener = null;
    }

    // 清空引用
    service._musicPlayerViewModel = null;
    service._context = null;

    // 销毁悬浮播放器管理器
    FloatingPlayerManager.dispose();

    _instance = null;
  }
}

/// 悬浮播放器路由观察器
/// 用于监听页面路由变化，自动管理悬浮播放器显示
class FloatingPlayerRouteObserver extends RouteObserver<PageRoute<dynamic>> {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    _handleRouteChange(route);
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    if (previousRoute != null) {
      _handleRouteChange(previousRoute);
    }
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    if (newRoute != null) {
      _handleRouteChange(newRoute);
    }
  }

  void _handleRouteChange(Route<dynamic> route) {
    if (route is PageRoute) {
      final routeName = route.settings.name;
      FloatingPlayerService.setCurrentRoute(routeName);
    }
  }
}

/// 悬浮播放器页面混入
/// 为页面提供便捷的悬浮播放器控制方法
mixin FloatingPlayerPageMixin<T extends StatefulWidget> on State<T> {
  /// 页面初始化时调用
  void initFloatingPlayer() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        FloatingPlayerService.exitPlayerPage(context);
      }
    });
  }

  /// 页面销毁时调用
  void disposeFloatingPlayer() {
    // 子类可以重写此方法进行特殊处理
  }

  /// 显示悬浮播放器
  void showFloatingPlayer() {
    FloatingPlayerService.showFloatingPlayer(context);
  }

  /// 隐藏悬浮播放器
  void hideFloatingPlayer() {
    FloatingPlayerService.hideFloatingPlayer();
  }

  /// 切换悬浮播放器显示状态
  void toggleFloatingPlayer() {
    FloatingPlayerService.toggleFloatingPlayer(context);
  }
}

/// 播放页面混入
/// 专门为播放页面提供的混入，自动管理进入/退出逻辑
mixin PlayerPageMixin<T extends StatefulWidget> on State<T> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        FloatingPlayerService.enterPlayerPage(context);
      }
    });
  }

  @override
  void dispose() {
    // 不传递 context，使用缓存的引用
    FloatingPlayerService.exitPlayerPage();
    super.dispose();
  }
}
